package com.atguigu.distributed.lock.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Conditor {
    private int number = 0;
    private Lock lock = new ReentrantLock();
    private Condition condition = this.lock.newCondition();

    public void incremeat() {
        lock.lock();
        try {
            while (number != 0) {
                condition.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName() + "\t" + number);
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void decremeat() {
        lock.lock();
        try {
            while (number==0){
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName()+"\t"+number);
            condition.signalAll();


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

public class ProdConsumer_TraditionDemo {
    public static void main(String[] args) {
        Conditor conditor = new Conditor();
        new Thread(()->{
            for (int i = 1; i <= 5; i++) {
                conditor.incremeat();
            }
        },"AAA").start();
        new Thread(()->{
            for (int i = 1; i <= 5; i++) {
                conditor.decremeat();
            }
        },"BBB").start();
        new Thread(()->{
            for (int i = 1; i <= 5; i++) {
                conditor.incremeat();
            }
        },"CCC").start();
        new Thread(()->{
            for (int i = 1; i <= 5; i++) {
                conditor.decremeat();
            }
        },"DDD").start();

    }
}
